import type { CompanyInfoDto, EleSignInfoDto } from '@/api/company/types'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import toNative from '@/utils/toNative'
import { Component, Emit, Prop, Ref, Watch } from 'vue-facing-decorator'
import Drawer from '@/components/drawer/Index'
import { getModelValue, renderForm, type FormModalDto } from '@/components/modal/Modal'
import {
    AreaRuleLimitCnEnum,
    DangerRuleCnEnum,
    FeeDeductionRuleTypeCnEnum,
    getKeyToEnum,
    InsureTypeCnEnum,
    RepeatRuleCnEnum,
    ReplaceRuleAllowTypeCnEnum,
    ReplaceRuleMethodCnEnum,
    RuleLimitCnEnum,
    ValidRuleTypeCnEnum
} from '@/const/enum'

import AreaSelect from '@/components/area-select/Index'
import ValidRule from './ValidRule'
import {
    Button,
    Checkbox,
    CheckboxGroup,
    Form,
    FormItem,
    Input,
    Radio,
    RadioGroup,
    Select,
    FormItemRest,
    message
} from 'ant-design-vue'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import { addInsureCompanyRule, editInsureCompanyRule, getInsureCompanyRuleDetail } from '@/api/insureCompanyRule'
import type { AddType } from '@/api/types'
import type { AddInsureCompanyRuleReqDto, EditInsureCompanyRuleReqDto, EffectRule, InsureCompanyRuleDetailDto, InsureCompanyRuleDto, PersonNumConfig, REffectRuleReq } from '@/api/insureCompanyRule/types'

@Component
export class DrawerAdd extends TableRender {
    @Prop() show!: boolean
    @Prop() type!: AddType
    @Prop() itemData?: InsureCompanyRuleDto

    @Ref formRef!: FormInstance

    showDrawer = false

    formData = {
        ruleName: '',
        insureType: InsureTypeCnEnum.长期保,
        // 年龄规则
        ageRule: {
            type: -1,
            startAge: null as number | null,
            endAge: null as number | null
        },
        dangerRule: {
            type: -1,
            dangerRule: null as number | null
        },
        companyAreaRuleType: -1,
        companyAreaRuleContent: [] as string[][], //客户区域
        serveCompanyAreaRuleContent: [] as string[][], // 派遣单位区域
        effectRule: [] as EffectRule[],
        deductRule: {
            insureTypeVal: FeeDeductionRuleTypeCnEnum.灵活方案,
            vaildType: ValidRuleTypeCnEnum.整点生效,
            insureTypeVal2: FeeDeductionRuleTypeCnEnum.月单,
            vaildType2: 2,
            deductTypeConfig: {
                moreThanDate: null as number | null,
                deductRatio: null as number | null
            }
        },
        replaceRule: {
            monthInsure: {
                allowReplace: null as number | null,
                replaceMethod: null as number | null
            }
        },
        repeatRule: [] as number[]
    }

    @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.showDrawer = this.show

        if (this.type === 'edit' || this.type === 'newAdd') {
            const detail = await this.getDetail(this.itemData?.id as number)
            this.formData.ruleName = detail.ruleName
            this.formData.insureType = detail.insureType
            this.formData.ageRule.type = detail.ageRule.startAge === -1 ? -1 : 1
            if (this.formData.ageRule.type === 1) {
                this.formData.ageRule.startAge = detail.ageRule.startAge
                this.formData.ageRule.endAge = detail.ageRule.endAge
            }

            this.formData.dangerRule.type = detail.dangerRule === -1 ? -1 : 1
            this.formData.dangerRule.dangerRule = detail.dangerRule

            this.formData.companyAreaRuleType = detail.companyAreaRule
            this.formData.companyAreaRuleContent = detail.companyAreaRuleContent?.map(i => i.split(','))
            this.formData.serveCompanyAreaRuleContent = detail.serveCompanyAreaRuleContent?.map(i => i.split(','))

            this.formData.effectRule = detail.effectRule
            this.formData.deductRule.deductTypeConfig = detail.deductRule.deductTypeConfig
            this.formData.replaceRule.monthInsure = detail.replaceRule.monthInsure
            this.formData.repeatRule = detail.repeatRule
        }
    }

    @Watch('showDrawer', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDrawer)
    }

    async getDetail(id: number) {
        const res = await getInsureCompanyRuleDetail({
            id
        })
        return res
    }

    async onSubmit() {
        const res = await this.formRef.validate()
        console.log('res', res)
        // 年龄规则
        if (!res.ageRule) {
            res.ageRule = {
                startAge: -1,
                endAge: -1
            }
        }
        // 出险规则
        if(!res.dangerRule) {
            res.dangerRule = -1
        }
        if (res.dangerRule!==-1) {
            res.dangerRule = res.dangerRule.dangerRule
        }
        // 区域规则
        res.companyAreaRule = this.formData.companyAreaRuleType
        res.serveCompanyAreaRule = this.formData.companyAreaRuleType
        if (res.companyAreaRule !== AreaRuleLimitCnEnum.不限) {
            res.companyAreaRuleContent = res.companyAreaRuleContent.map((i: string[]) => i.join(','))
            res.serveCompanyAreaRuleContent = res.serveCompanyAreaRuleContent.map((i: string[]) => i.join(','))
        }
        // 查重规则
        res.repeatRule = res.repeatRule.join(',')

        if (this.type === 'add' || this.type === 'newAdd') {
            await addInsureCompanyRule(res)
        } else {
            res.id = this.itemData?.id
            await editInsureCompanyRule(res as EditInsureCompanyRuleReqDto)
        }

        this.showDrawer = false
        message.success('添加成功')
        this.handleRefresh()
    }

    render() {
        return (
            <>
                <Drawer
                    v-model:show={this.showDrawer}
                    size={900}
                    title="保司规则"
                    destroyOnClose
                    resetStyle
                    showClose
                    v-slots={{
                        default: () => {
                            return (
                                <div>
                                    <Form ref="formRef" model={this.formData}>
                                        <FormItem label="规则名称" name="ruleName" required>
                                            <Input
                                                v-model:value={this.formData.ruleName}
                                                placeholder="请输入规则名称"
                                            />
                                        </FormItem>
                                        <FormItem label="保险产品" name="insureType" required>
                                            <RadioGroup v-model:value={this.formData.insureType}>
                                                <Radio value={InsureTypeCnEnum.长期保}>
                                                    长期保
                                                </Radio>
                                            </RadioGroup>
                                        </FormItem>
                                        <FormItem label="年龄规则" required>
                                            <div class={`flex flex-wrap items-baseline ${this.formData.ageRule.type === 1 ? '-mb-24px' : ''}`}>
                                                <RadioGroup v-model:value={this.formData.ageRule.type}>
                                                    {getKeyToEnum(RuleLimitCnEnum).map((i) => {
                                                        return (
                                                            <Radio value={i.value}>{i.label}</Radio>
                                                        )
                                                    })}
                                                </RadioGroup>
                                                {this.formData.ageRule.type === 1 && (
                                                    <>
                                                        <FormItem
                                                            class="inline-block"
                                                            name={['ageRule', 'startAge']}
                                                            rules={[{ required: true, message: '请输入最小年龄' }]}
                                                        >
                                                            <Input
                                                                v-model:value={
                                                                    this.formData.ageRule.startAge
                                                                }
                                                                class="!w-100px mx-5px ml-10px"
                                                            ></Input>
                                                        </FormItem>
                                                        <span class="px-10px">岁≤ 员工年龄 ≤</span>
                                                        <FormItem
                                                            class="inline-block"
                                                            name={['ageRule', 'endAge']}
                                                            rules={[{ required: true, message: '请输入最大年龄' }]}
                                                        >
                                                            <Input
                                                                v-model:value={this.formData.ageRule.endAge}
                                                                class="!w-100px mx-5px"
                                                            ></Input>
                                                        </FormItem>
                                                        <span>岁</span>
                                                    </>
                                                )}
                                            </div>
                                        </FormItem>
                                        <FormItem label="出险规则" required>
                                            <div class={`flex flex-wrap items-baseline ${this.formData.dangerRule.type !== -1 ? '-mb-24px' : ''}`}>
                                                <RadioGroup
                                                    v-model:value={this.formData.dangerRule.type}
                                                >
                                                    <Radio value={-1}>不限</Radio>
                                                    <Radio value={1}>限制</Radio>
                                                </RadioGroup>
                                                {this.formData.dangerRule.type !== -1 && (
                                                    <>
                                                        <span class="ml-10px">
                                                            员工出险时，可以
                                                        </span>
                                                        <FormItem
                                                            class="inline-block"
                                                            name={['dangerRule', 'dangerRule']}
                                                            rules={[
                                                                { required: true, message: '请选择出险规则' },
                                                            ]}
                                                        >
                                                            <Select
                                                                v-model:value={
                                                                    this.formData.dangerRule.dangerRule
                                                                }
                                                                class="!w-100px mx-5px"
                                                                options={getKeyToEnum(
                                                                    DangerRuleCnEnum,
                                                                    false,
                                                                    ['次月', '理赔结束']
                                                                )}
                                                            ></Select>
                                                        </FormItem>
                                                        <span>减保</span>
                                                    </>
                                                )}
                                            </div>
                                        </FormItem>
                                        <FormItem label="区域规则" required>
                                            <div class="w-full flex flex-wrap items-baseline">
                                                <div>
                                                    <RadioGroup
                                                        v-model:value={
                                                            this.formData.companyAreaRuleType
                                                        }
                                                    >
                                                        {getKeyToEnum(AreaRuleLimitCnEnum).map(
                                                            (i) => {
                                                                return (
                                                                    <Radio value={i.value}>
                                                                        {i.label}
                                                                    </Radio>
                                                                )
                                                            }
                                                        )}
                                                    </RadioGroup>
                                                </div>
                                                {this.formData.companyAreaRuleType ===
                                                    AreaRuleLimitCnEnum.允许投保区域 && (
                                                    <>
                                                        <div class="w-full">
                                                            <div class="flex mt-16px w-full">
                                                                <div class="w-140px text-right flex-shrink-0">
                                                                    客户允许区域：
                                                                </div>
                                                                <FormItem class="inline-block align-baseline w-full" name="companyAreaRuleContent" rules={[{required: true, message: '请选择区域'}]}>
                                                                    <AreaSelect
                                                                        v-model:value={
                                                                            this.formData
                                                                                .companyAreaRuleContent
                                                                        }
                                                                        class="flex-1"
                                                                    />
                                                                </FormItem>
                                                            </div>
                                                            <div class="flex mt-16px w-full">
                                                                <div class="w-140px text-right flex-shrink-0">
                                                                    派遣单位允许区域：
                                                                </div>
                                                                <FormItem class="inline-block align-baseline w-full" name="serveCompanyAreaRuleContent" rules={[{required: true, message: '请选择区域'}]}>
                                                                    <AreaSelect
                                                                        v-model:value={
                                                                            this.formData
                                                                                .serveCompanyAreaRuleContent
                                                                        }
                                                                        class="flex-1"
                                                                    />
                                                                </FormItem>
                                                            </div>
                                                        </div>
                                                    </>
                                                )}

                                                {this.formData.companyAreaRuleType ===
                                                    AreaRuleLimitCnEnum.禁止投保区域 && (
                                                    <>
                                                        <div class="w-full">
                                                            <div class="flex mt-16px w-full">
                                                                <div class="w-140px text-right flex-shrink-0">
                                                                    客户限制区域：
                                                                </div>
                                                                <FormItem class="inline-block align-baseline w-full" name="companyAreaRuleContent" rules={[{required: true, message: '请选择区域'}]}>
                                                                    <AreaSelect
                                                                        v-model:value={
                                                                            this.formData
                                                                                .companyAreaRuleContent
                                                                        }
                                                                        class="flex-1"
                                                                    />
                                                                </FormItem>
                                                            </div>
                                                            <div class="flex mt-16px w-full">
                                                                <div class="w-140px text-right flex-shrink-0">
                                                                    派遣单位限制区域：
                                                                </div>
                                                                <FormItem class="inline-block align-baseline w-full" name="serveCompanyAreaRuleContent" rules={[{required: true, message: '请选择区域'}]}>
                                                                    <AreaSelect
                                                                        v-model:value={
                                                                            this.formData
                                                                                .serveCompanyAreaRuleContent
                                                                        }
                                                                        class="flex-1 w-full"
                                                                    />
                                                                </FormItem>
                                                            </div>
                                                        </div>
                                                    </>
                                                )}
                                            </div>
                                        </FormItem>
                                        <FormItem label="生效规则" required>
                                            <ValidRule
                                                v-model:value={this.formData.effectRule}
                                            />
                                        </FormItem>
                                        <FormItem label="扣费规则" required>
                                            <div class="mb-10px">
                                                <Select
                                                    v-model:value={
                                                        this.formData.deductRule.insureTypeVal
                                                    }
                                                    disabled
                                                    class="!w-100px mx-5px"
                                                    options={getKeyToEnum(
                                                        FeeDeductionRuleTypeCnEnum
                                                    )}
                                                ></Select>
                                                <span>根据生效时间按天扣除费用，</span>
                                                <Select
                                                    v-model:value={
                                                        this.formData.deductRule.vaildType
                                                    }
                                                    disabled
                                                    class="!w-100px mx-5px"
                                                    options={getKeyToEnum(ValidRuleTypeCnEnum)}
                                                ></Select>
                                                <span>
                                                    的立即扣除保费（第一次激活次日生效，次日扣费）
                                                </span>
                                            </div>
                                            <div class="">
                                                <Select
                                                    v-model:value={
                                                        this.formData.deductRule.insureTypeVal2
                                                    }
                                                    disabled
                                                    class="!w-100px mx-5px"
                                                    placeholder="请选择"
                                                    options={getKeyToEnum(
                                                        FeeDeductionRuleTypeCnEnum
                                                    )}
                                                ></Select>
                                                <span>按月立即扣除费用，</span>
                                                <Select
                                                    v-model:value={
                                                        this.formData.deductRule.vaildType2
                                                    }
                                                    placeholder="请选择"
                                                    disabled
                                                    class="!w-100px mx-5px"
                                                    options={[{ label: '自然月', value: 2 }]}
                                                ></Select>
                                                <FormItem
                                                    class="inline-block"
                                                    name={['deductRule', 'deductTypeConfig', 'moreThanDate']}
                                                    rules={[{ required: true, message: '请输入生效日期' }]}
                                                >
                                                    <Input
                                                        v-model:value={
                                                            this.formData.deductRule.deductTypeConfig.moreThanDate
                                                        }
                                                        placeholder="请输入"
                                                        class="!w-100px mx-5px"
                                                    />
                                                </FormItem>
                                                <span>日之后生效，扣除</span>
                                                <FormItem
                                                    class="inline-block"
                                                    name={['deductRule', 'deductTypeConfig', 'deductRatio']}
                                                    rules={[{ required: true, message: '请输入月保费' }]}
                                                >
                                                    <Input
                                                        v-model:value={
                                                            this.formData.deductRule.deductTypeConfig.deductRatio
                                                        }
                                                        placeholder="请输入"
                                                        class="!w-100px mx-5px"
                                                    />
                                                </FormItem>
                                                <span>倍月保费</span>
                                            </div>
                                        </FormItem>

                                        <FormItem label="替换规则" required>
                                            <div class="">
                                                <span>月单员工在保期间，减保不退钱</span>
                                                <FormItem class="inline-block align-baseline" name={['replaceRule', 'monthInsure', 'allowReplace']} rules={[{ required: true, message: '请选择是否允许替换人员' }]}>
                                                    <Select
                                                        v-model:value={
                                                            this.formData.replaceRule.monthInsure.allowReplace
                                                        }
                                                        placeholder="请选择"
                                                        class="!w-100px mx-5px"
                                                        options={getKeyToEnum(
                                                            ReplaceRuleAllowTypeCnEnum
                                                        )}
                                                    ></Select>
                                                </FormItem>
                                                <span>替换员工，和被替换的在保员工</span>
                                                <FormItem class="inline-block align-baseline" name={['replaceRule', 'monthInsure', 'replaceMethod']} rules={[{ required: true, message: '请选择替换方式' }]}>
                                                    <Select
                                                        v-model:value={
                                                            this.formData.replaceRule.monthInsure.replaceMethod
                                                        }
                                                        placeholder="请选择"
                                                        class="!w-100px mx-5px"
                                                        options={getKeyToEnum(ReplaceRuleMethodCnEnum)}
                                                    ></Select>
                                                </FormItem>
                                                <span>相同</span>
                                            </div>
                                        </FormItem>
                                        <FormItem label="查重规则" name="repeatRule" required>
                                            <div>
                                                <CheckboxGroup v-model:value={this.formData.repeatRule}>
                                                    {getKeyToEnum(RepeatRuleCnEnum).map((i) => {
                                                        return (
                                                            <Checkbox value={i.value}>
                                                                {i.label}
                                                            </Checkbox>
                                                        )
                                                    })}
                                                </CheckboxGroup>
                                            </div>
                                            {/* <div>
                                                <Select
                                                    class="!w-100px mx-5px"
                                                    options={getKeyToEnum(ValidRuleTypeCnEnum)}
                                                ></Select>
                                            </div> */}
                                        </FormItem>
                                        {/* <FormItem label="费率浮动规则" name="ruleName" required>
                                            <div>
                                                <Input class="!w-100px" type="text" />
                                                <span> ≤理赔率≤ </span>
                                                <Select
                                                    class="!w-100px mx-5px"
                                                    options={getKeyToEnum(ValidRuleTypeCnEnum)}
                                                ></Select>
                                                <span>保费费率</span>
                                                <Input class="!w-100px" type="text" />
                                            </div>
                                        </FormItem> */}
                                    </Form>
                                </div>
                            )
                        },
                        footer: () => {
                            return (
                                <Button type="primary" onClick={this.onSubmit}>
                                    确定
                                </Button>
                            )
                        }
                    }}
                ></Drawer>
            </>
        )
    }
}

export default toNative<{type: AddType, itemData: InsureCompanyRuleDto }, { refresh: () => void }>(DrawerAdd)
